package com.skanda.sys.aop;

import com.skanda.sys.annotation.Lock;
import com.skanda.sys.componnet.DistributedLock;
import com.skanda.sys.exception.BizException;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class LockAop {

    @Autowired
    DistributedLock distributedLock;

    @Around(value = "@annotation(lock)")
    public Object lock(ProceedingJoinPoint pj, Lock lock) throws Throwable {
        Object[] args = pj.getArgs();

        Object ret = null;
        Boolean lockRet = false;
        try{
            lockRet = distributedLock.lock(lock.key(),lock.value());
            log.info("获取锁:{},结果:{}",lock.key(),lockRet);
            if(!lockRet){
                log.info("获取锁失败.");
                throw BizException.UNFINISH_REQUEST;
            }
        }catch (Exception e){
            throw BizException.UNFINISH_REQUEST;
        }
        try {
            ret = pj.proceed(args);
        }catch (Exception e){
            log.error("执行异常={}", e.getMessage());
            throw e;
        }finally {
            if(lockRet){
                distributedLock.unLock(lock.key());
            }
        }
        return  ret;
    }
}
